package com.cskaoyan.mall.user.controller;

import com.cskaoyan.mall.common.constant.ResultCodeEnum;
import com.cskaoyan.mall.common.result.Result;
import com.cskaoyan.mall.common.util.IpUtil;
import com.cskaoyan.mall.user.consts.UserCodeEnum;
import com.cskaoyan.mall.user.consts.UserConstants;
import com.cskaoyan.mall.user.dto.UserLoginDTO;
import com.cskaoyan.mall.user.dto.UserLoginInfoDTO;
import com.cskaoyan.mall.user.query.UserInfoParam;
import com.cskaoyan.mall.user.service.UserService;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;
/**
 * @author Macro_Ray
 * @since 2024/6/19 下午2:33
 */
@RestController
@RequestMapping("user")
public class LoginController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedissonClient redissonClient;

    /**
     * 登录
     */
    @PostMapping("login")
    public Result<UserLoginDTO> login(@RequestBody UserInfoParam userInfo, HttpServletRequest request) {

        // 1. 获取发起请求的主机的ip地址
        String ipAddress = IpUtil.getIpAddress(request);

        // 2. 生成存储用户登录信息的Token字符串(redis key)
        String tokenStr = UUID.randomUUID().toString().replaceAll("-", "");

        UserLoginDTO login = userService.login(userInfo, ipAddress, tokenStr);

        if (login == null) {
            // 如果用户名或密码匹配失败
            return Result.build(null, UserCodeEnum.USER_LOGIN_CHECK_FAIL);
        }
        return Result.ok(login);
    }

    /**
     * 退出登录
     * @param request
     */
    @GetMapping("logout")
    public Result logout(HttpServletRequest request){

        String tokenStr = request.getHeader(UserConstants.USER_LOGIN_TOKEN_HEADER);

        RBucket<UserLoginInfoDTO> bucket = redissonClient.getBucket(UserConstants.USER_LOGIN_KEY_PREFIX + tokenStr);
        bucket.delete();

        return Result.ok();
    }
}
